from urllib import request,error,parse
import  json


def fanyi(keyword):
    url ='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    #定义请求参数并转码
    data = {'i': keyword,'from':'AUTO','to': 'AUTO','smartresult': 'dict','client': 'fanyideskweb','salt': '1542276300318','sign': 'e3f4a0e549d1617f4a99da771757f4a7','doctype': 'json','version': '2.1','keyfrom': 'fanyi.web','action': 'FY_BY_REALTIME','typoResult': 'false'}
    data = parse.urlencode(data)


    # 设置header 头信息
    headers = {'Content-Length':len(data)}

    #创建请求，发送请求，爬取信息
    req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)

    try:
        res = request.urlopen(req)
        #解析结果
        str_json=res.read().decode("utf-8")
        myjson=json.loads(str_json)
        print(myjson['translateResult'][0][0]['tgt'])##翻译结果
    except Exception as e:
        if hasattr(e,'reason'):
            print(e.reason)
        if hasattr(e,'code'):
            print(e.code)

if __name__=='__main__':
    while True:
        keyword = input("请输入要翻译的词：")
        if keyword == 'q':
            break
        fanyi(keyword)
